package cn.xm.basic.controller;

import cn.xm.basic.result.AjaxResult;
import cn.xm.basic.utils.FastdfsUtil;
import com.sun.xml.internal.ws.util.FastInfosetUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/fast_dfs")
public class FastDfsController {

    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestPart MultipartFile file) throws IOException {
        // 获取文件扩展名
        String filename = file.getOriginalFilename();
        String extension = filename.substring(filename.indexOf(".") + 1);
        // 将文件转换为数组
        byte[] bytes = file.getBytes();
        // 上传文件
        String path = FastdfsUtil.upload(bytes, extension);
        return AjaxResult.me().setResultObj(path);
    }

    @GetMapping("/del")
    public AjaxResult delete(@RequestParam String filePath) throws IOException {
        // 获取文件的组名
        String filePath2 = filePath.substring(1); // group/...
        String groupName = filePath2.substring(0, filePath2.indexOf("/")); // group
        String fileName = filePath2.substring(filePath2.indexOf("/") + 1);
        FastdfsUtil.delete(groupName,fileName);
        return AjaxResult.me();

    }
}
